<link rel="stylesheet" href="${request.contextPath}/static/oms/default/plugins/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" href="${request.contextPath}/static/oms/iframe/plugins/fileupload/css/jquery.fileupload-ui.css">
<link type="text/css" href="${request.contextPath}/static/oms/iframe/plugins/jeditor/css/jeditor.css" rel="stylesheet" />
<link href="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/css/image-picker.css"  rel="stylesheet" type="text/css" />
<div class="row">
	<div class="col-md-12">
		<form id="add-form" class="form-horizontal" action="${request.contextPath}/notepad/favorite/add" method="post" onsubmit="return false">
			<div class="box-body" >
				<div class="form-group">
					<label for="favoriteUsername" class="col-sm-2 control-label">用户名</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="username" id="favoriteUsername" placeholder="输入用户名...">
					</div>
					<label id="favoriteCategoryIdLabel" for="favoriteCategoryId" class="col-sm-2  control-label">所属类别</label>
					<div class="col-sm-4">
						<div class="input-group">
							<input type="hidden" class="form-control" id="favoriteCategoryId" name="favoriteCategoryId"  value="" >
							<input type="text" class="form-control"  id="favoriteCategoryName" value="" placeholder="选择所属类别...">
							<span class="input-group-addon"><i class="glyphicon glyphicon-remove" style="color: #FF0000;" id="favoriteCategoryIdClear"></i></span>
							<div id="favoriteCategoryContent" class="favoriteCategoryContent" style="position: absolute; left: 0; top: 25px; display: none;z-index: 999999;">
								<ul id="favoriteCategoryTree" class="ztree" style="margin-top: 10px;
															border: 1px solid #d6e0df;
															background: #fbfbfb;
															width: 220px;
															height: 360px;
															overflow-y: scroll;
															overflow-x: auto; -moz-user-select: none;">
								</ul>
							</div>
						</div>
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteTitleLabel" for="favoriteTitle" class="col-sm-2 control-label">标题</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="title" id="favoriteTitle" placeholder="输入标题...">
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteKeywordsLabel" for="favoriteKeywords" class="col-sm-2 control-label">关键字</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="keywords" id="favoriteKeywords" placeholder="输入关键字...">
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteDescriptionLabel" class="col-sm-2 control-label" >概要</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="description" id="favoriteDescription" placeholder="输入概要...">
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteThumbnailLabel" for="favoriteThumbnail" class="col-sm-2 control-label">缩略图</label>
					<div class="col-sm-7">
						<input type="text" class="form-control" name="thumbnail" id="favoriteThumbnail" placeholder="输入缩略图...">
					</div>
					<div class="col-sm-3">
						<span class="btn btn-success fileinput-button">
							<i class="glyphicon glyphicon-plus"></i>
							<span>选择文件</span>
							<input id="favoriteThumbnailFileupload"  class="fileinput-button"  type="file" name="file"  data-url="/system/config/file/add?type=1" multiple>
						 </span>
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteWhetherReminderLabel" for="favoriteWhetherReminder" class="col-sm-2  control-label">是否提醒</label>
					<div class="col-sm-4">
						<select class="form-control" id="favoriteWhetherReminder"  name="whetherReminder" style="width: 100%;" placeholder="选择是否提醒...">
						</select>
					</div>
					<label id="favoriteAccessLevelLabel" for="favoriteAccessLevel" class="col-sm-2  control-label">访问级别</label>
					<div class="col-sm-4">
						<select class="form-control" id="favoriteAccessLevel"  name="accessLevel" style="width: 100%;" placeholder="选择访问级别...">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteSortOrderLabel" for="favoriteSortOrder" class="col-sm-2  control-label">排序号</label>
					<div class="col-sm-4">
						<input  class="form-control" name="sortOrder" id="favoriteSortOrder" type="number" placeholder="排序号...">
					</div>
					<label id="favoriteStatusLabel" for="favorite-status" class="col-sm-2  control-label">状态</label>
					<div class="col-sm-4">
						<select class="form-control" id="favorite-status"  name="status" style="width: 100%;" placeholder="选择状态...">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteContentLabel" class="col-sm-2 control-label" >内容</label>
					<div class="col-sm-10">
						<textarea  name="content" id="favoriteContent" data-toggle="jeditor" data-upload="/system/config/file/add?type=1" placeholder="输入内容...">
						</textarea>
					</div>
				</div>
				<div class="form-group">
					<label id="favoriteRemarkLabel" class="col-sm-2 control-label">备注</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="remark" id="favoriteRemark" placeholder="输入备注...">
					</div>
				</div>
				<div class="error-message text-center" id="addFormErrorMsgContainer">
					<span class="error-icon"></span>
					<span id="addFormErrorMsg" class="error-msg" ></span>
				</div>
			</div>
			<div class="box-body">
				<div class="pull-right">
					<button type="submit" class="btn btn-primary btn-sm" ><i class="fa fa-save"></i> 保存</button>
					<button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><i class="fa fa-close"></i> 取消</button>
				</div>
			</div>
		</form>
	</div>
</div>
<!-- 配置文件 -->
<script type="text/javascript" src="${request.contextPath}/static/oms/default/plugins/zTree/jquery.ztree.all.js"></script>
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/jeditor/js/jeditor.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/vendor/jquery.ui.widget.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/js/imagePicker.js"></script>
<script type="text/javascript">
function ajaxSubmit(form) {
	
	var $form = $(form);
	
	if ($form.length === 1 && $form.validate()) {
		$.post(form.action, $form.serialize(),
			function(result) {
				if (result.success) {
					$("#lgModal").modal('hide');
		        	alertMsg(result.message,"success");
                    dataGridReload();
				} else {
					$form.find(".error-msg").show();
					$form.find(".error-msg").html(result.message);
				}
			}, 'json');
	}
}

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: null
        }
    },
    async: {
        enable: true,
        url:"/notepad/favorite/category/tree",
        dataFilter:function (treeId, parentNode, responseData) {
            if (responseData) {
                for(var i =0; i < responseData.length; i++) {
                    responseData[i].url = null;
                }
            }
            return responseData;
        }
    },
    callback:{
        onAsyncSuccess:function (event, treeId) {
            var node = $.fn.zTree.getZTreeObj(treeId).getNodeByParam("id", $("#favoriteCategoryId").val());
            if(node){
                $("#favoriteCategoryName").val(node.name);
            }
        },
        onClick :function (event, treeId, treeNode) {
            $("#favoriteCategoryId").val(treeNode.id);
            $("#favoriteCategoryName").val(treeNode.name);
            $('#favoriteCategoryContent').hide();
        }
    }
};

$(function() {

    $("#favoriteCategoryName").on('click',function () {
        var $favoriteCategoryContent = $('#favoriteCategoryContent');
        $favoriteCategoryContent.css("display")==='none'?$favoriteCategoryContent.show():$favoriteCategoryContent.hide();
    });
    $("#favoriteCategoryContent").mouseleave(function () {
        $('#favoriteCategoryContent').hide();
    });

    $("#favoriteCategoryIdClear").on('click',function () {
        $("#favoriteCategoryId").val("");
        $("#favoriteCategoryName").val("");
    });

    $("#favoriteUsername").on('blur',function () {
        var $this = $(this);
        if($this.val()){
            setting.async.url="/notepad/favorite/category/tree?username="+$this.val();
            $.fn.zTree.init($('#favoriteCategoryTree'), setting);
		}
    });


    $("#favoriteThumbnail").imageDynamicPicker();
    $("#favoriteThumbnailFileupload").fileupload({
        url: "/system/config/file/add",
        autoUpload: true,
        dataType: 'json',
        acceptFileTypes: /\.(jpg|png|gif)$/i, //浏览器支持File API才有效
        maxFileSize: 2097152, //2M，浏览器支持File API才有效
        send: function(e, data){
            alertMsg('上传中...',"success");
        },
        done: function (e, data) {
            alertMsg("上传成功", "success");
            $("#favoriteThumbnail").val(data._response.result.data.url);
        },
        fail: function(e, data) {
            alertMsg("上传失败", "success");
        }
    });

    $("#favoriteWhetherReminder").select2({
        data: WhetherStore,
        placeholder: "请选择...",
        language: "zh-CN",
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    });
    $("#favoriteAccessLevel").select2({
        data: AccessLevelStore,
        placeholder: "请选择...",
        language: "zh-CN",
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    });
    $("#favorite-status").select2({
        data: StatusStore,
        placeholder: "请选择...",
        language: "zh-CN",
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    });

    $('[data-toggle="jeditor"]').each(function() {

        var $this = $(this)
        var editor = new jeditor($this);
        var uploadUrl = $this.data('upload');
        editor.config.uploadImgUrl= uploadUrl;
        editor.config.hideLinkImg = true;
        editor.config.uploadImgFileName='file';
        editor.config.containerHeight=400;
        editor.config.uploadImgFns = {
            onload:function (resultText, xhr) {
                var resultObj = eval('(' + resultText + ')');
                console.info('上传结束，返回结果为 ' + resultText);
                var editor = this;
                var originalName = editor.uploadImgOriginalName || '';  // 上传图片时，已经将图片的名字存在 editor.uploadImgOriginalName
                var img;
                if (!resultObj.success) {
                    // 提示错误
                    console.warn('上传失败：' + resultObj.message);
                    alert(resultObj.message);
                } else {
                    console.log('上传成功，即将插入编辑区域，结果为：' + resultText);

                    // 将结果插入编辑器
                    img = document.createElement('img');
                    img.onload = function () {
                        var html = '<img src="' + resultObj.data.urlFull + '" alt="' + originalName + '" style="max-width:100%;"/>';
                        editor.command(null, 'insertHtml', html);

                        console.log('已插入图片，地址 ' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.onerror = function () {
                        console.error('使用返回的结果获取图片，发生错误。请确认以下结果是否正确：' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.src = resultObj.data.urlFull;
                }

            }
        };
        editor.create();
    });

    var $addForm = $("#add-form");
    $addForm.validate({
		rules: {
            username: {
				required: true
			},
			title: {
				required: true
			}
		},
		messages: {
            username:{
				required:"用户名不能为空！"
			},
            title:{
				required:"标题不能为空！"
			}
		},
		submitHandler:ajaxSubmit,
		errorLabelContainer:"#addFormErrorMsgContainer",
		wrapper:"li",
		showErrors:function(errorMap,errorList) {
			if(errorList.length>0){
				$addForm.find(".error-msg").html(errorList[0].message);
			}else{
				$addForm.find(".error-msg").html("");
			}
		},
		onkeyup: false
	});
});
</script>